﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SMS.Data;
using Wicresoft.SMS.Common;

namespace Wicresoft.SMS.Gateway.Host
{
    class SendEmailTask : Task
    {
        protected IServiceConfigProvider _configProvider;
        protected IEmailDataAccess _emaildataaccess;
        protected IExchangeServerInfo _esinfo;

        public SendEmailTask(IServiceConfigProvider configProvider, IEmailDataAccess emaildataaccess, IExchangeServerInfo esinfo)
        {
            try
            {
                _configProvider = configProvider;
                _emaildataaccess = emaildataaccess;
                _esinfo = esinfo;
                // MailOperation.InstanceExchangeServerAPI(_esinfo.ESServerVersion, _esinfo.ESServerURL, _esinfo.ESUsername, _esinfo.ESPassword, _esinfo.ESDomain, _esinfo.ESEmail);
                MailOperation.InstanceSmtpClient(_esinfo.ESUsername, _esinfo.ESPassword, _esinfo.ESHost, _esinfo.ESPort, _esinfo.ESEmail);
            }
            catch (Exception ex)
            {
                DBLog.Exception("Wicresoft.SMS.Gateway.Host.SendEmailTask ", ex);
            }
           
        }

        protected override void ExecuteCore()
        {
            while (_scanAble && _configProvider.SendEmailTaskEnable == 1)
            {
                try
                {
                    QueryDB2SendEmail();
                    System.Threading.Thread.Sleep(
                        _configProvider.SendEmailTaskSpan < GlobalFactory.TaskSpanBorder ? GlobalFactory.TaskSpanBorder : _configProvider.SendEmailTaskSpan);
                }
                catch (Exception ex)
                {
                    DBLog.Exception("Wicresoft.SMS.Gateway.Host.SendEmailTask.ExecuteCore ", ex);
                }
               
            }
        }

        private void QueryDB2SendEmail()
        {
           // DBLog.Debug("Entrying QueryDB2SendEmail");
            DBLog.Debug("Entrying QueryDB2SendEmail");
            var mails = _emaildataaccess.GetUnsendMails();
            if (mails != null)
            {
                foreach (var item in mails)
                {
                    Common.EmailInfo em = new Common.EmailInfo();
                    em.Subject = item.Subject;
                    em.To = item.To;
                    em.CC = item.CC;
                    em.BCC = item.BCC;
                    em.Body = item.Content;
                    item.State = MailOperation.SendEmail(em);
                    if (item.State)
                        item.ModifyTime = DateTime.Now;
                }
                _emaildataaccess.MarkEmailStateAsSent(mails);
            }
            DBLog.Debug("leaving QueryDB2SendEmail");
        }
    }
}
